package com.lm.socket.example;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;

public class NioClient {
    public static void main(String[] args) {
        try {
            // 1. 创建 SocketChannel
            SocketChannel socketChannel = SocketChannel.open();
            socketChannel.configureBlocking(false);

            // 2. 连接服务器
            if (!socketChannel.connect(new InetSocketAddress("localhost", 8080))) {
                while (!socketChannel.finishConnect()) {
                    System.out.println("Connecting to server...");
                }
            }

            System.out.println("Connected to server!");

            // 3. 发送数据
            String message = "Hello NIO Server!";
            ByteBuffer buffer = ByteBuffer.wrap(message.getBytes());
            socketChannel.write(buffer);

            // 4. 接收服务器响应
            buffer.clear();
            socketChannel.read(buffer);
            buffer.flip();
            System.out.println("Received from server: " + new String(buffer.array(), 0, buffer.limit()));

            socketChannel.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
